/**
 * Pollinations Image API Client
 * 
 * A simple client for the Pollinations Image API for uniapp
 */

/**
 * Generates an image URL from a text prompt using the Pollinations Image API
 * 
 * @param {string} prompt - The text description of the image to generate
 * @param {Object} options - Additional options for image generation
 * @param {string} [options.model] - Model name to use for generation
 * @param {number} [options.seed] - Seed for reproducible results
 * @param {number} [options.width=1024] - Width of the generated image
 * @param {number} [options.height=1024] - Height of the generated image
 * @returns {Object} - Object containing the image URL and metadata
 */
export async function generateImageUrl(prompt, options = {}) {
    if (!prompt || typeof prompt !== 'string') {
      throw new Error('Prompt is required and must be a string');
    }
  
    const { 
      model, 
      seed, 
      width = 1024, 
      height = 1024,
    } = options;
    
    // 构建查询参数
    let queryParams = '';
    if (model) queryParams += `${queryParams ? '&' : ''}model=${encodeURIComponent(model)}`;
    if (seed !== undefined) queryParams += `${queryParams ? '&' : ''}seed=${encodeURIComponent(seed)}`;
    if (width) queryParams += `${queryParams ? '&' : ''}width=${encodeURIComponent(width)}`;
    if (height) queryParams += `${queryParams ? '&' : ''}height=${encodeURIComponent(height)}`;
    
    // 构建URL
    const encodedPrompt = encodeURIComponent(prompt);
    const baseUrl = 'https://image.pollinations.ai';
    let url = `${baseUrl}/prompt/${encodedPrompt}`;
    
    // 添加查询参数（如果存在）
    if (queryParams) {
      url += `?${queryParams}`;
    }
    
    // 直接返回URL，保持简单
    return {
      imageUrl: url,
      prompt,
      width,
      height,
      model: model || 'flux', // 默认模型是flux
      seed
    };
  }
  
  /**
   * Generates an image from a text prompt and returns the image data as base64
   * 
   * @param {string} prompt - The text description of the image to generate
   * @param {Object} options - Additional options for image generation
   * @param {string} [options.model] - Model name to use for generation
   * @param {number} [options.seed] - Seed for reproducible results
   * @param {number} [options.width=1024] - Width of the generated image
   * @param {number} [options.height=1024] - Height of the generated image
   * @returns {Promise<Object>} - Object containing the base64 image data, mime type, and metadata
   */
  export async function generateImage(prompt, options = {}) {
    // 首先，生成图片URL
    const result = await generateImageUrl(prompt, options);
    
    try {
      // 使用uni.request获取图片
      return new Promise((resolve, reject) => {
        uni.request({
          url: result.imageUrl,
          method: 'GET',
          responseType: 'arraybuffer', // 请求二进制数据
          success: (res) => {
            if (res.statusCode === 200) {
              // 将二进制数据转换为base64字符串
              // 注意：不同平台可能需要不同的处理方式
              let base64Data;
              
              // #ifdef APP-PLUS || H5
              // 在APP和H5环境下可以使用arrayBuffer转base64
              const arrayBuffer = res.data;
              base64Data = uni.arrayBufferToBase64(arrayBuffer);
              // #endif
              
              // #ifdef MP
              // 小程序环境无法直接处理二进制数据，可以保存到临时文件再处理
              const fs = uni.getFileSystemManager();
              const tempFilePath = `${wx.env.USER_DATA_PATH}/temp_image_${Date.now()}.png`;
              fs.writeFileSync(tempFilePath, res.data, 'binary');
              base64Data = fs.readFileSync(tempFilePath, 'base64');
              // 清理临时文件
              fs.unlinkSync(tempFilePath);
              // #endif
              
              // 确定MIME类型
              const contentType = res.header && res.header['content-type'] || 'image/png';
              
              resolve({
                data: base64Data,
                mimeType: contentType,
                metadata: {
                  prompt: result.prompt,
                  width: result.width,
                  height: result.height,
                  model: result.model,
                  seed: result.seed
                }
              });
            } else {
              reject(new Error(`Failed to fetch image: ${res.statusCode}`));
            }
          },
          fail: (err) => {
            console.error('Error generating image:', err);
            reject(err);
          }
        });
      });
    } catch (error) {
      console.error('Error generating image:', error);
      throw error;
    }
  }
  
  /**
   * List available image generation models from Pollinations API
   * 
   * @returns {Promise<Object>} - Object containing the list of available models
   */
  export async function listModels() {
    try {
      const baseUrl = 'https://image.pollinations.ai';
      console.log(`Fetching models from ${baseUrl}/models`);
      
      return new Promise((resolve, reject) => {
        uni.request({
          url: `${baseUrl}/models`,
          method: 'GET',
          success: (res) => {
            if (res.statusCode === 200) {
              resolve({ models: res.data });
            } else {
              reject(new Error(`Error fetching models: ${res.statusCode}`));
            }
          },
          fail: (err) => {
            console.error('Error in listModels:', err);
            reject(err);
          }
        });
      });
    } catch (error) {
      console.error('Error in listModels:', error);
      throw error;
    }
  }
  
  // 仅在直接运行此文件时执行（例如，使用Node.js）
  if (typeof require !== 'undefined' && require.main === module) {
    // 示例用法
    const run = async () => {
      try {
        // 示例：生成图片URL
        const imageResult = await generateImageUrl('A beautiful sunset over the ocean');
        console.log('Generated Image URL:', imageResult);
        
        // 示例：列出可用模型
        const modelsResult = await listModels();
        console.log('Available Models:', modelsResult);
      } catch (error) {
        console.error('Error:', error);
      }
    };
    
    run();
  }